using System;
using System.Web;
using System.Web.UI;
using System.Web.SessionState;
using System.Collections.Specialized;

using GURUCORE.Lib.Core.Text;


namespace GURUCORE.Portal.Core.Controller
{	
	//[System.Diagnostics.DebuggerStepThroughAttribute()]
	public class FrontController : IHttpHandler, IRequiresSessionState
	{
		public FrontController()
		{
		}

        RemapURL myRemapURL = new RemapURL();

        /// <summary>
        /// This is the paramname for Page=  ,now is = __page.
        /// </summary>
        public const string PARAM_PAGE = "__page";
        /// <summary>
        /// This is the GURUCORE Controller page, the one define in the web.config for ASP.NET render after  GURUCORE Framework render the configured pagelets.
        /// </summary>
        public const string FRONT_CONTROLLER_PAGE = "Portal.aspx";

        /// NULL PAGE, to indicate the front controller ignore this page to rewrite		
        public const string EXTENSIONLESS_PAGE = "EXTENSIONLESS.aspx";


#if(DEBUG) // OPTIMIZING
        DateTime dtmRequestTimeStart = DateTime.Now;
#endif


		public void ProcessRequest(HttpContext p_oContext) 
		{
            // HACK: lockevn is still hacking here
            string sPreRewriteRawURL = p_oContext.Request.Url.ToString();
            string sPageExtension = ((WebsiteConfiguration)WebsiteApplication.GetInstance().GetSharedObject(WebsiteConfiguration.GLOBAL_CACHE_KEY)).PageExtension;
            // END HACK: lockevn is still hacking here

            // prepare for handling
			int nPageOfs = p_oContext.Request.ApplicationPath.Length + 1;
			if (p_oContext.Request.ApplicationPath == "/")
			{
				nPageOfs--;
			}
            string sPage = p_oContext.Request.Path.Substring(nPageOfs,p_oContext.Request.Path.Length - nPageOfs);

            if (sPage == EXTENSIONLESS_PAGE)
            {
                #region Process the Exntensionless page
                
                // REVIEW: GURUCORE not test
                // do the extension less page rewrite
                // DEBUG:				GURUCORE.Lib.Core.Logging.FileLogger.Pln(sPage);

                string sPathAndQueryWithoutVirtualPath = p_oContext.Request.Url.PathAndQuery.Substring(p_oContext.Request.ApplicationPath.Length);

                // DEBUG:				GURUCORE.Lib.Core.Logging.FileLogger.Pln(sPathAndQueryWithoutVirtualPath);

                string sResultURL = "~/" + FRONT_CONTROLLER_PAGE + "?" +
                    PARAM_PAGE + "=" + myRemapURL.Remap(RemapURL.EXTENSIONLESS, sPathAndQueryWithoutVirtualPath, sPage.Replace(".", "\\."));
                // DEBUG:				GURUCORE.Lib.Core.Logging.FileLogger.Pln(sResultURL + "-------------");


                p_oContext.RewritePath(sResultURL);
                IHttpHandler oHandler = PageParser.GetCompiledPageInstance("~/" + FRONT_CONTROLLER_PAGE, null, p_oContext);
                oHandler.ProcessRequest(p_oContext);

                #endregion
            }
            else  // normal page
            {
                // start build the actual real QueryString
                string sQueryString = PARAM_PAGE + "=" + p_oContext.Request.Path.Substring(nPageOfs, p_oContext.Request.Path.Length - nPageOfs) + "&";
                foreach (string sQueryKey in p_oContext.Request.QueryString)
                {
                    sQueryString += sQueryKey + "=" + p_oContext.Request.QueryString[sQueryKey] + "&";
                }
                sQueryString = sQueryString.Substring(0, sQueryString.Length - 1);

                // rewrite the acutual URL to ASPNET process
                p_oContext.RewritePath("~/" + FRONT_CONTROLLER_PAGE + "?" + sQueryString);

                // this function will make new PageController object, assign to oHandler
                IHttpHandler oHandler = PageParser.GetCompiledPageInstance("~/" + FRONT_CONTROLLER_PAGE, null, p_oContext);
                ((PageController)oHandler).PreRewriteRawURL = sPreRewriteRawURL;
                              
                              
                oHandler.ProcessRequest(p_oContext);
            }


#if(DEBUG) // OPTIMIZING
                string myString = "FrontController.ProcessRequest " + DateTime.Now.Subtract(dtmRequestTimeStart).TotalMilliseconds + "ms<br>";
                p_oContext.Response.Write(myString);
#endif

        }   // end function


		public bool IsReusable
		{ 
			get 
			{ 
				return false;
			} 
		}
	
	}
}
